#!/usr/bin/env node

const { Command } = require("commander");
const WebBuilder = require("./builders/web-builder");
const V1ToV2Upgrader = require("./upgraders/V1-to-V2-upgrader");
const IdeSetup = require("./installer/lib/ide-setup");
const path = require("path");

const program = new Command();

program
    .name("sdat-build")
    .description("SDAT-Method 构建工具，用于创建 Web 包")
    .version("4.0.0");

program
    .command("build")
    .description("为代理和团队构建 Web 包")
    .option("-a, --agents-only", "仅构建代理包")
    .option("-t, --teams-only", "仅构建团队包")
    .option("-e, --expansions-only", "仅构建扩展包")
    .option("--no-expansions", "跳过构建扩展包")
    .option("--no-clean", "跳过清理输出目录")
    .action(async (options) => {
        const builder = new WebBuilder({
            rootDir: process.cwd(),
        });

        try {
            if (options.clean) {
                console.log("正在清理输出目录...");
                await builder.cleanOutputDirs();
            }

            if (options.expansionsOnly) {
                console.log("正在构建扩展包...");
                await builder.buildAllExpansionPacks({ clean: false });
            } else {
                if (!options.teamsOnly) {
                    console.log("正在构建代理包...");
                    await builder.buildAgents();
                }

                if (!options.agentsOnly) {
                    console.log("正在构建团队包...");
                    await builder.buildTeams();
                }

                if (!options.noExpansions) {
                    console.log("Building expansion pack bundles...");
                    await builder.buildAllExpansionPacks({ clean: false });
                }
            }

            console.log("构建成功完成！");
        } catch (error) {
            console.error("构建失败:", error.message);
            process.exit(1);
        }
    });

program
    .command("build:expansions")
    .description("为所有扩展包构建 Web 包")
    .option("--expansion <name>", "仅构建特定的扩展包")
    .option("--no-clean", "跳过清理输出目录")
    .action(async (options) => {
        const builder = new WebBuilder({
            rootDir: process.cwd(),
        });

        try {
            if (options.expansion) {
                console.log(`正在构建扩展包: ${options.expansion}`);
                await builder.buildExpansionPack(options.expansion, {
                    clean: options.clean,
                });
            } else {
                console.log("正在构建所有扩展包...");
                await builder.buildAllExpansionPacks({ clean: options.clean });
            }

            console.log("扩展包构建成功完成！");
        } catch (error) {
            console.error("扩展包构建失败:", error.message);
            process.exit(1);
        }
    });

program
    .command("list:agents")
    .description("列出所有可用的代理")
    .action(async () => {
        const builder = new WebBuilder({ rootDir: process.cwd() });
        const agents = await builder.resolver.listAgents();
        console.log("可用的代理:");
        agents.forEach((agent) => console.log(`  - ${agent}`));
    });

program
    .command("list:expansions")
    .description("列出所有可用的扩展包")
    .action(async () => {
        const builder = new WebBuilder({ rootDir: process.cwd() });
        const expansions = await builder.listExpansionPacks();
        console.log("可用的扩展包:");
        expansions.forEach((expansion) => console.log(`  - ${expansion}`));
    });

program
    .command("validate")
    .description("验证代理和团队配置")
    .action(async () => {
        const builder = new WebBuilder({ rootDir: process.cwd() });
        try {
            // Validate by attempting to build all agents and teams
            const agents = await builder.resolver.listAgents();
            const teams = await builder.resolver.listTeams();

            console.log("正在验证代理...");
            for (const agent of agents) {
                await builder.resolver.resolveAgentDependencies(agent);
                console.log(`  ✓ ${agent}`);
            }

            console.log("\n正在验证团队...");
            for (const team of teams) {
                await builder.resolver.resolveTeamDependencies(team);
                console.log(`  ✓ ${team}`);
            }

            console.log("\n所有配置均有效！");
        } catch (error) {
            console.error("验证失败:", error.message);
            process.exit(1);
        }
    });

program
    .command("upgrade")
    .description("将 SDAT-Method V1 项目升级到 V2")
    .option(
        "-p, --project <path>",
        "V1 项目的路径（默认为当前目录）"
    )
    .option("--dry-run", "显示将要更改的内容但不实际修改")
    .option("--no-backup", "跳过创建备份（不推荐）")
    .action(async (options) => {
        const upgrader = new V1ToV2Upgrader();
        await upgrader.upgrade({
            projectPath: options.project,
            dryRun: options.dryRun,
            backup: options.backup,
        });
    });

program.parse();
